package com.tianqu.tms.core.base;

import java.util.StringTokenizer;
import java.util.Vector;

import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.Level;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;


/**
 * TMS
 */

public class TmsLogFilter extends Filter {
	/***/
	private boolean acceptOnMatch = false;
	/***/
	private Vector<Level> levels = new Vector<Level>(5);
	/***/
	private String levelString;

	/**
	 * level
	 */
	public int decide(LoggingEvent event) {
		if (levels == null){
			return Filter.NEUTRAL;
		}
		Level lev = event.getLevel();
		boolean matchOccured = false;

		int size = levels.size();
		for (int i = 0; i < size; i++) {
			Level l = (Level) levels.elementAt(i);
			if (l != null && l.equals(lev)) {
				matchOccured = true;
				break;
			}
		}
		if (!matchOccured){
			return Filter.DENY;
		}
		if (acceptOnMatch) {
			return Filter.ACCEPT;
		} else {
			return Filter.NEUTRAL;
		}
	}

	/**
	 * 
	 * @return
	 */
	public boolean getAcceptOnMatch() {
		return acceptOnMatch;
	}

	/**
	 * 
	 * @param acceptonMatch
	 */
	public void setAcceptOnMatch(boolean acceptonMatch) {
		this.acceptOnMatch = acceptonMatch;
	}

	/**
	 * 
	 * @param str
	 */
	public void setLevels(String str) {
		levelString = str;

		StringTokenizer token = new StringTokenizer(levelString, ",");
		while (token.hasMoreTokens()) {
			Level l = OptionConverter.toLevel(token.nextToken(), null);
			if (l != null) {
				levels.add(l);
			}
		}
	}

	/**
	 * 
	 * @return
	 */
	public String getLevels() {
		return levelString;
	}
}
